package controller

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo/v4"
	"github.com/labstack/gommon/log"
	"law_case_api/dto"
	"law_case_api/models"
	"law_case_api/services"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// @Summary 登录接口
// @Tags 用户
// @Accept plain
// @Produce plain
// @Param Login body dto.LoginReq true " "
// @Success 200 {object} models.BaseResult
// @Failure 400 {object} models.BaseResult
// @Router /wzj/login [post]
func Login(c echo.Context) error {
	resp := models.BaseResult{
		Code: 200,
	}
	loginReq := dto.LoginReq{}
	if err := c.Bind(&loginReq); err != nil {
		resp.Code = 400
		resp.Message = err.Error()
		return c.JSON(http.StatusBadRequest, resp)
	}
	//参数验证
	if len(strings.Trim(loginReq.UserName, "")) == 0 {
		resp.Code = 400
		resp.Message = "用户名不能为空"
		return c.JSON(http.StatusOK, resp)
	}
	if len(strings.Trim(loginReq.UserPwd, "")) == 0 {
		resp.Code = 400
		resp.Message = "密码不能为空"
		return c.JSON(http.StatusOK, resp)
	}

	// Set custom claims
	claims := &models.JwtCustomClaims{
		IsLaw: loginReq.IsLaw,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(time.Hour * 72).Unix(),
		},
	}
	//是否是律师登录
	if loginReq.IsLaw {
		law := services.LawService{}
		if res, err := law.GetLawByName(loginReq.UserName); err != nil {
			log.Error("GetLawByName -- 查询律师信息失败：", err)
			resp.Code = 400
			resp.Message = "查询律师信息失败"
			return c.JSON(http.StatusOK, resp)
		} else {
			if res.Id == 0 {
				resp.Code = 400
				resp.Message = "律师不存在，请联系管理员创建"
				return c.JSON(http.StatusOK, resp)
			}
			if res.LawPwd != loginReq.UserPwd {
				resp.Code = 400
				resp.Message = "密码不正确"
				return c.JSON(http.StatusOK, resp)
			}
			claims.UserName = res.LawName
			claims.UserId = strconv.FormatInt(res.Id, 10)
		}
	} else {
		customer := services.CustomerService{}
		if res, err := customer.GetCustomerInfoByUnifySocialCreditCode(loginReq.UserName); err != nil {
			log.Error("GetCustomerInfoByUnifySocialCreditCode -- 查询客户信息失败：", err)
			resp.Code = 400
			resp.Message = "查询客户信息失败"
			return c.JSON(http.StatusOK, resp)
		} else {
			if res.Id == 0 {
				resp.Code = 400
				resp.Message = "客户不存在，请联系管理员创建"
				return c.JSON(http.StatusOK, resp)
			}
			if res.CustomerPwd != loginReq.UserPwd {
				resp.Code = 400
				resp.Message = "密码不正确"
				return c.JSON(http.StatusOK, resp)
			}
			claims.UserName = res.CustomerName
			claims.UserId = strconv.FormatInt(res.Id, 10)
		}
	}

	// Create token with claims
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	// Generate encoded token and send it as response.
	t, err := token.SignedString([]byte("secret"))
	if err != nil {
		return err
	}
	resp.Data = t
	return c.JSON(http.StatusOK, resp)
}
